﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Device.Base;
using Device.Base.Comm;

namespace Device
{
    /// <summary>
    /// 设备基类
    /// </summary>
    public abstract class DeviceBase : CommBase, IDevice
    {
        protected DeviceBase(ITransmission communication) : base(communication)
        {
            Interval = 1000;
        }
        /// <summary>
        /// 取值状态
        /// </summary>
        public bool State;
        /// <summary>
        /// 间隔时间 ms
        /// </summary>
        public int Interval { get; set; }
        /// <summary>
        /// 取值
        /// </summary> 
        protected abstract void GetValue(); 
        /// <summary>
        /// 开始检测
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            if (!State)
            {
                State = true;
                Task.Factory.StartNew(() =>
                {
                    while (State)
                    {
                        GetValue();//取值
                        Thread.Sleep(Interval);//休眠
                    }
                });

            }

            return State; 
        }
        /// <summary>
        /// 停止检测
        /// </summary>
        /// <returns></returns>
        public bool Stop()
        {
            State = false;
            return true;
        }
    }
}
